<script setup>
import {
    Edit, Delete, Link, Download, Check, Close
} from '@element-plus/icons-vue'
import axios from 'axios';
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus'
import {
    addstaffservice, deletestaffservice, updatestaffservice, getAllservice
} from '@/api/chance.js'

import {
    getallclientservice, getpartkeymanservice, getKeyManByID
} from '@/api/client.js'

import {
    addtraceuserservice
} from '@/api/traceuser.js'

import {
    addTraceservice
} from '@/api/trace.js'


import {
    userInfoService
} from '@/api/user.js'


import {
    getallareaservice, getalluserservice, moveservice, getallareamasterservice, getallnotareamasterservice,
    getAllAreaMasterNotChooseservice, getAllNotAreaMasterNotChooseservice
} from '@/api/book.js'

//控制添加分类弹窗
const dialogVisible = ref(false)
const dialogVisible3 = ref(false)
const dialogVisible4 = ref(false)
//分页条数据模型
//const pageNum = ref(1)//当前页
const total = ref(20)//总条数
const total2 = ref(20)
const total3 = ref(20)
//const pageSize = ref(3)//每页条数
//文章分类数据模型

//定义变量，控制标题
const title = ref('')

//交通路线列表数据模型
const majors = ref([

])
const areamasters = ref([])

const allareamasters = ref([]);



const mortals = ref([])
const keymans = ref([])
const formref = ref(null); //表单校验
//与后端交互的json数据
const pathmodel = ref({
    chancename: null,
    projectname: null,
    phase: null,
    areaname: null,
    budget: null,
    areas: null,
    chancedatetime: null,
    comment: null,
    keymen: null,
    clientcompanyid: null,
    stock: null,
    clue: null
})


const pathmodel2 = ref({

    chanceid: null,
    userid: null,
    visitor: null,
    thing: null,
    situation: null,
    comment: null,
    visittime: null
})
const temp = ref({
    keyman: []
})





const findmodel = ref({
    pageNum: 1,
    pageSize: 5,
    str: '',
    findType: null
})

const findmodel2 = ref({
    pageNum: 1,
    pageSize: 10086,
    str: ''
})

const findmodel3 = ref({
    pageNum: 1,
    pageSize: 10086,
    str: ''
})
const findmodelkey = ref({
    clientcompanyid: null,
    str: '',
})
const keymanOptions = ref({

})

const getAllKeyman = async () => {
    let result = await getpartkeymanservice(findmodelkey.value);

    console.log("客户是" + findmodelkey.value.clientcompanyid);
    console.log("关键人物数据是" + JSON.stringify(result.data));
    keymanOptions.value = result.data;

}


const clientcompanyOptions = ref({

})


const addCloseChance = async () => {

    formref.value.validate(async (valid) => {
        if (!valid) {
            ElMessage.error('信息填写不完整！');
        }
        else {

            let result = await addTraceservice(pathmodel2.value);



            let result2 = await updatestaffservice(pathmodel.value);
            if (result2.code != 0) ElMessage.error(result2.message ? result2.message : '关闭失败')
            else ElMessage.success('关闭成功')
            //再次调用getAllCategory，获取所有文章分类
            stafflist();


            if (result.code == 0) {
                ElMessage.success("关闭成功")
                dialogVisible4.value = false;

                stafflist();
            }
            else ElMessage.error(result.message ? result.message : '关闭失败')


        }
    });
}



const closeChance = async (row) => {

    title.value = '关闭机会原因';
    dialogVisible4.value = true;
    pathmodel2.value.chanceid = row.chanceid;
    pathmodel2.value.userid = row.user.id;

    console.log("这行的信息 = " + JSON.stringify(row));

    pathmodel.value.chancename = row.chancename;
    pathmodel.value.projectname = row.projectname;
    pathmodel.value.phase = "已关闭";
    pathmodel.value.areaname = row.areaname;
    pathmodel.value.budget = row.budget;
    pathmodel.value.areas = row.areas;

    const date = new Date(row.chancedatetime);

    date.setHours(date.getHours() + 8);
    pathmodel.value.chancedatetime = date.toISOString();;
    pathmodel.value.comment = row.comment;
    pathmodel.value.keymen = row.keymen;
    pathmodel.value.clientcompanyid = row.clientcompanyid;
    pathmodel.value.stock = row.stock;
    pathmodel.value.clue = row.clue;

    pathmodel.value.chanceid = row.chanceid;







}


    // 监听 dialogVisible4 的变化
    watch(dialogVisible4, (newVal) => {
      if (!newVal) {
        pathmodel2.value.situation = '';
      }
    });

const updatestaff = async () => {
    //console.log(pathmodel.value);


    let result = await updatestaffservice(pathmodel.value);
    console.log("分配结果= " + result.data);

    stafflist();
}



const getAllClient = async () => {
    let result = await getallclientservice();

    //console.log("客户数据是" + JSON.stringify(result.data));
    clientcompanyOptions.value = result.data;

}

const handleClientChange = (clientId) => {
    // 找到对应的 item 对象
    const selectedItem = clientcompanyOptions.value.find(item => item.id === clientId);
    if (selectedItem) {
        findmodelkey.value.clientcompanyid = pathmodel.value.clientcompanyid;
        pathmodel.value.areaname = selectedItem.pet;
        getAllKeyman();
    }
};


const areasOptions = ref({

})


const getAllArea = async () => {
    let result = await getallareaservice();

    console.log("片区数据是" + JSON.stringify(result.data));
    areasOptions.value = result.data;

}

const clueOptions = ref({

})


const getAllUser = async () => {
    let result = await getalluserservice();

    console.log("员工数据是" + JSON.stringify(result.data));
    clueOptions.value = result.data;

}


const stafflist = async () => {
    console.log(findmodel.value);
    let userresult2 = await userInfoService();
    findmodel.value.findType = userresult2.data.id;
    let result = await getAllservice(findmodel.value);
    //console.log("销售机会信息:" + JSON.stringify(result.data));

    total.value = result.data.total;
    majors.value = result.data.items;


    let result2 = await getallareamasterservice(findmodel2.value)
    total2.value = result2.data.total;

    allareamasters.value = result2.data.items;


    // console.log("majors.value = " +JSON.stringify(majors.value))
}
stafflist();
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
    findmodel.value.pageSize = size;
    stafflist();
}
const onSizeChange2 = (size) => {
    findmodel2.value.pageSize = size;
    areaMove();
}
const onSizeChange3 = (size) => {
    findmodel3.value.pageSize = size;
    personmove();
}

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
    findmodel.value.pageNum = num;
    stafflist();
}
const onCurrentChange2 = (num) => {
    findmodel2.value.pageNum = num;
    areaMove();
}
const onCurrentChange3 = (num) => {
    findmodel3.value.pageNum = num;
    personmove();
}


const cleardata = () => {
    findmodel.value.str = '';
    findmodel.value.pageNum = 1;
    stafflist();
}
//表单校验
const rules = {
    chancename: [
        { required: true, message: '请输入机会名称', trigger: 'blur' },
    ],
    projectname: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
    ],
    budget: [
        { required: true, message: '请输入预算', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value < 0) {
                    callback(new Error('预算不能为负数'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ],
    areas: [
        { required: true, message: '请选择片区', trigger: 'blur' },
    ],
    chancedatetime: [
        { required: true, message: '请选择销售机会日期', trigger: 'blur' },
    ],
    clientcompanyid: [
       
    ],
    stock: [
        { required: true, message: '请输入存货', trigger: 'blur' },
    ],
    clue: [
        { required: true, message: '请输线索来源', trigger: 'blur' },
    ],
    comment: [
        { required: true, message: '请输入备注', trigger: 'blur' },
    ]
}

const rules4 = {

    situation: [
    { required: true, message: '请输入原因', trigger: 'blur' },
    ]
}


const areaMove = async (row) => {

    findmodel2.value.str = row.chanceid;
    console.log("row.chanceid = " + row.chanceid)
    let result = await getAllAreaMasterNotChooseservice(findmodel2.value)

    areachanceModel.value.chanceid = row.chanceid;
    total2.value = result.data.total;

    areamasters.value = result.data.items;
    console.log("areamasters.value = " + JSON.stringify(areamasters.value));
    dialogVisible.value = true;
    title.value = '传递片区';
}

const personmove = async (row) => {
    findmodel3.value.str = row.chanceid;
    let result = await getAllNotAreaMasterNotChooseservice(findmodel3.value);
    areachanceModel.value.chanceid = row.chanceid;
    total3.value = result.data.total;

    mortals.value = result.data.items;
    // console.log("Before mapping, areamasters.value = " + JSON.stringify(areamasters.value));
    // console.log("Before mapping, mortals.value = " + JSON.stringify(mortals.value));

    // 确保 mortals.value 是一个数组
    if (Array.isArray(mortals.value)) {
        mortals.value = mortals.value.map(mortal => {
            // 找到与 mortal.areaid 相匹配的 areamaster
            const areamaster = allareamasters.value.find(am => am.areaid === mortal.areaid);
            if (areamaster) {
                // 如果找到匹配的 areamaster，扩展 mortal 对象
                return {
                    ...mortal,
                    boss: areamaster.name,
                    bossphone: areamaster.phone
                };
            }
            // 如果没有找到匹配的 areamaster，返回原始的 mortal 对象
            return mortal;
        });
    } else {
        console.error('mortals.value is not an array:', mortals.value);
    }

    console.log("After mapping, mortals.value = " + JSON.stringify(mortals.value));
    dialogVisible3.value = true;
    title.value = '分配员工';


    pathmodel.value.chancename = row.chancename;
    pathmodel.value.projectname = row.projectname;
    pathmodel.value.phase = '已分配';
    pathmodel.value.areaname = row.areaname;
    pathmodel.value.budget = row.budget;
    pathmodel.value.areas = row.areas;


    pathmodel.value.chancedatetime = row.chancedatetime;
    const date = new Date(pathmodel.value.chancedatetime);

    date.setHours(date.getHours() + 8);
    pathmodel.value.chancedatetime = date.toISOString();


    pathmodel.value.comment = row.comment;
    pathmodel.value.keymen = row.keymen;
    pathmodel.value.clientcompanyid = row.clientcompanyid;
    pathmodel.value.stock = row.stock;
    pathmodel.value.clue = row.clue;


    pathmodel.value.chanceid = row.chanceid;




};




const areachanceModel = ref({
    chanceid: null,
    userid: null
})




const addorupdate = async () => {

    updatestaff();
    for (const r of selectrowsdata.value) {
        // 假设每个选中的行对象都有一个id属性
        areachanceModel.value.userid = r.id;
        // 这里你可以执行其他需要的操作，比如更新数据库等
        let result = await addtraceuserservice(areachanceModel.value);
        if (result.code == 0) {
            ElMessage.success("添加成功");
        } else {
            ElMessage.error(result.message ? result.message : '添加失败');
            // 如果添加失败，可以选择在这里中断循环
            // break;
        }
    }
    // 所有操作完成后，关闭对话框并刷新列表
    dialogVisible.value = false;
    dialogVisible3.value = false;
}



const selectrowsdata = ref([]);
const handleSelectionChange = (val) => {
    selectrowsdata.value = val;
    console.log("已选片区为 = " + JSON.stringify(selectrowsdata.value))
}






</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>销售机会分配及传递</span>

            </div>
        </template>

        <!-- 搜索表单 -->
        <el-form>
            <el-form-item label="查询条件:">
                <el-input v-model="findmodel.str" placeholder="请输入查询内容" style="width: 300px"></el-input>
                <el-button type="primary" @click="stafflist" style="margin-left: 15px;">搜索</el-button>
                <el-button @click="cleardata">重置</el-button>
            </el-form-item>
        </el-form>
        <!-- 文章列表 -->
        <el-table :data="majors" style="width: 100%">
            <el-table-column label="机会名称" prop="chancename"  width="150"></el-table-column>
            <el-table-column label="销售机会主题" prop="projectname"></el-table-column>


            <el-table-column label="线索来源" prop="user.name"  width="150"></el-table-column>
            <el-table-column label="发布日期" prop="chancedatetime"  width="250"></el-table-column>
            <el-table-column label="行业" prop="areaname" width="150"></el-table-column>
            <el-table-column label="机会状态" prop="phase" width="80"></el-table-column>
            <el-table-column label="操作" width="260">
                <template #default="{ row }">
                            <el-button plain type="primary" @click="areaMove(row)"
                                :disabled="row.phase === '已关闭'">传递片区</el-button>
                  
                      
                            <el-button plain type="primary" @click="personmove(row)"
                                :disabled="row.phase === '已关闭'">分配员工</el-button>
              
                        <el-button :icon="Close" circle plain type="primary" @click="closeChance(row)"
                            :disabled="row.phase === '已关闭'"></el-button>
                  
                </template>

            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>

        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="findmodel.pageNum" v-model:page-size="findmodel.pageSize"
            :page-sizes="[5, 10, 15, 20]" layout="jumper, total, sizes, prev, pager, next" background :total="total"
            @size-change="onSizeChange" @current-change="onCurrentChange"
            style="margin-top: 20px; justify-content: flex-end" />


    </el-card>

    <!-- 添加分类弹窗 -->


    <el-dialog v-model="dialogVisible" :title="title" width="60%">

        <el-table :data="areamasters" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="片区名称" prop="areaname"></el-table-column>
            <el-table-column label="片区负责人" prop="name"></el-table-column>
            <el-table-column label="联系方式" prop="phone"></el-table-column>

            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>


        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addorupdate"> 确认 </el-button>
            </span>
        </template>

    </el-dialog>



    <el-dialog v-model="dialogVisible3" :title="title" width="60%">

        <el-table :data="mortals" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="员工名称" prop="name"></el-table-column>
            <el-table-column label="员工联系方式" prop="phone"></el-table-column>
            <el-table-column label="直属上级" prop="boss"></el-table-column>
            <el-table-column label="上级联系方式" prop="bossphone"></el-table-column>

            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>

        <!-- 分页条 -->

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible3 = false">取消</el-button>
                <el-button type="primary" @click="addorupdate"> 确认 </el-button>
            </span>
        </template>

    </el-dialog>

    <el-dialog v-model="dialogVisible4" :title="title" width="50%">
        <el-form :model="pathmodel2" ref="formref" :rules="rules4" label-width="100px" style="padding-right: 30px">
            <div>

                <el-form-item label="原因" prop="situation">
                    <el-input type="textarea" :rows="8" v-model="pathmodel2.situation" style="width: 600px"></el-input>
                </el-form-item>
            </div>

        </el-form>


        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible4 = false">取消</el-button>
                <el-button type="primary" @click="addCloseChance"> 确认 </el-button>
            </span>
        </template>
    </el-dialog>



</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>